package gncom.qr;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class StoryPage extends ListActivity {

	public static ArrayList<StoryVO> list;
	SpeechListAdapter list_adapter;
	public static String qr;

	private Context mContext;

	private ArrayList<Boolean> mExpanded = new ArrayList<Boolean>();
	private boolean isModify = false; // 수정중

	private SQLiteDatabase mDatabase;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.storypage);
		openData();

		Log.i("qr", "StoryPage.............");

		LayoutInflater inflater = getLayoutInflater();

		final View custLayout = inflater.inflate(R.layout.custtoast,
				(ViewGroup) findViewById(R.id.toast_layout));

		// ////////2011.10.31 update
		if (getIntent().getStringExtra("url") != null) {
			qr = getIntent().getStringExtra("qrcode");
			saveURL(getIntent().getStringExtra("url"), qr);
			list = null;
			list = getStoryInfoList();
			if (getIntent().getStringExtra("url").startsWith("http://") || getIntent().getStringExtra("url").startsWith("https://")) {
				// launchIntent(new Intent(Intent.ACTION_VIEW,
				// Uri.parse(getIntent().getStringExtra("url"))));
				closeData();
				startActivity(new Intent(this, WebViewerPage.class).putExtra(
						"url", getIntent().getStringExtra("url")));
				
				finish();
			} else {
				closeData();
				startActivity(new Intent(this, TextViewerPage.class).putExtra(
						"text", getIntent().getStringExtra("url")));
				// Toast.makeText(this,
				// "유효하지 않은 인터넷 주소입니다.\n다시 스켄하세요.",Toast.LENGTH_SHORT).show();

				// Toast toast = new Toast(StoryPage.this);
				// toast.setDuration(Toast.LENGTH_SHORT);
				// toast.setGravity(Gravity.RIGHT, 0, 0);
				// toast.setView(custLayout);
				// toast.show();
				finish();

			}
		} else {
			list = null;
			list = getStoryInfoList();
		}

		list_adapter = new SpeechListAdapter(this);
		setListAdapter(list_adapter);

		Button storyEditBtn = (Button) findViewById(R.id.storyEditBtn);
		storyEditBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Arrays.fill(list_adapter.states, false);
				if (list_adapter.isModify()) {

					setCheckedDelete();
					list_adapter.notifyDataSetChanged();
					list = null;
					list = getStoryInfoList();
				}
				list_adapter.editToggle((Button) v);
			}
		});

		// spinner_category
		setSpinner_category();

		closeData();

	}// end onCreate()

	private void setSpinner_category() {
		ArrayList<String> category_list = getCategoryList();
		category_list.set(0, "전체");
		Spinner spinner_category = (Spinner) findViewById(R.id.spinner_category);
		spinner_category.setAdapter(new ArrayAdapter<String>(this,
				R.layout.storypage_spinner, category_list));

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, category_list);
		adapter.setDropDownViewResource(R.layout.storypage_spinner);
		spinner_category.setAdapter(adapter);

		spinner_category
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View v,
							int arg2, long arg3) {
						list = null;
						String category_name = ((TextView) v).getText()
								.toString();
						if (category_name.compareTo("전체") == 0) {
							list = getStoryInfoList();
						} else {
							list = getStoryInfoList(category_name);
						}
						list_adapter = new SpeechListAdapter(StoryPage.this);
						setListAdapter(list_adapter);

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
	}//end setSpinner_category()

	public ArrayList<String> getCategoryList() {
		openData();
		ArrayList<String> list = new ArrayList<String>();

		Cursor c = mDatabase.query("categoryNames", null, null, null, null,
				null, "c_id asc");
		//startManagingCursor(c);
		c.moveToFirst();
		while (!(c.isAfterLast())) {
			list.add(c.getString(c.getColumnIndex("name")));
			c.moveToNext();
		}
		c.close();
		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, 1, 0, null).setIcon(R.drawable.category_setting);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		
		case 1:
			Intent intent = new Intent(this, SettingPage.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		}
		return true;
	}

	protected void setCheckedDelete() {
		openData();
		int result = 0;
		for (int i = 0; i < list_adapter.delete_ids.length; i++) {
			if (list_adapter.delete_ids[i] != null) {
				result = mDatabase.delete("qrStory", "id=?",
						new String[] { list_adapter.delete_ids[i] });
			}

		}

		Log.i("story", "delete result.." + result);

	}

	void launchIntent(Intent intent) {
		if (intent != null) {
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			Log.i("qr", "StoryPage.intent....!null........"
					+ getIntent().getStringExtra("url"));
			try {
				startActivity(intent);

			} catch (ActivityNotFoundException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.app_name);
				builder.setMessage(R.string.msg_intent_failed);
				builder.setPositiveButton(R.string.button_ok, null);
				builder.show();
			} finally {
				finish();
			}
		} else {
			Log.i("qr", "StoryPage.intent....null........"
					+ getIntent().getStringExtra("url"));
		}
	}

	private ArrayList<StoryVO> getStoryInfoList() {
		openData();
		Cursor c = mDatabase.query("qrStory", null, null, null, null, null,
				"id desc");

		if (c.getCount() == 0) {
			Toast.makeText(this, "저장된 이용내역이 없습니다.", 0).show();
		}

		ArrayList<StoryVO> data = new ArrayList<StoryVO>();
		StoryVO vo = null;
		c.moveToFirst();
		while (!(c.isAfterLast())) {
			vo = new StoryVO();
			vo.setId(c.getInt(c.getColumnIndex("id")));
			vo.setUrl(c.getString(c.getColumnIndex("url")));
			vo.setWebTitle(c.getString(c.getColumnIndex("webTitle")));
			vo.setCdate(c.getLong(c.getColumnIndex("cdate")));
			vo.setStory(c.getString(c.getColumnIndex("story")));
			vo.setQr_img(c.getString(c.getColumnIndex("qrcode")));

			data.add(vo);
			c.moveToNext();
		}
		c.close();
		return data;
	}

	private ArrayList<StoryVO> getStoryInfoList(String category) {
		openData();

		Cursor c = mDatabase.query("qrStory", null, "categoryName=?",
				new String[] { category }, null, null, "id desc");

		if (c.getCount() == 0) {
			Toast.makeText(this, "저장된 이용내역이 없습니다.", 0).show();
		}

		ArrayList<StoryVO> data = new ArrayList<StoryVO>();
		StoryVO vo = null;
		c.moveToFirst();
		while (!(c.isAfterLast())) {
			vo = new StoryVO();
			vo.setId(c.getInt(c.getColumnIndex("id")));
			vo.setUrl(c.getString(c.getColumnIndex("url")));
			vo.setWebTitle(c.getString(c.getColumnIndex("webTitle")));
			vo.setCdate(c.getLong(c.getColumnIndex("cdate")));
			vo.setStory(c.getString(c.getColumnIndex("story")));
			vo.setQr_img(c.getString(c.getColumnIndex("qrcode")));

			data.add(vo);
			c.moveToNext();
		}
		c.close();
		return data;
	}

	private void saveURL(String url, String qrcode) {
		// 1.DB 연결.
		openData();

		// 2.입력.
		ContentValues values = new ContentValues();
		values.put("url", url);
		values.put("webTitle", "");
		values.put("qrcode", qrcode);
		values.put("cdate", System.currentTimeMillis());
		values.put("categoryName", "기타...");

		mDatabase.insert("qrStory", null, values);

		// 3.서버로 입력.
		// 아직 미구현...
	}

	private void openData() {
		Log.i("story", "openData().......");
		mDatabase = openOrCreateDatabase("storyInfo",
				SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor c = mDatabase.rawQuery(
				"select name from sqlite_master where type=? and name=?",
				new String[] { "table", "qrStory" });

		if (c.getCount() == 0) {
			mDatabase
					.execSQL("create table qrStory(id integer primary key autoincrement,url text,qrcode text,cdate long,story text);");
		}
		
		

		// column add (alter table test add column categoryName text)
		c = mDatabase.query("qrStory", null, null, null, null, null, null);

		Log.i("story",
				"c.getColumnIndex()...." + c.getColumnIndex("categoryName"));

		if (c.getColumnIndex("categoryName") == -1) {
			mDatabase
					.execSQL("alter table qrStory add column categoryName text;");
			ContentValues values = new ContentValues();
			values.put("categoryName", "기타...");
			mDatabase.update("qrStory", values, "id>?", new String[] { "0" });
		}
		// column add
		if (c.getColumnIndex("webTitle") == -1) {
			mDatabase
					.execSQL("alter table qrStory add column webTitle text;");
			
		}

//		startManagingCursor(c);
		c.close();
		
		Cursor c2 = mDatabase.rawQuery("select name from sqlite_master where type=? and name=?", new String[] {"table", "categoryNames"});
		if (c2.getCount() == 0) {
			mDatabase.execSQL("create table categoryNames(c_id integer primary key autoincrement, name text);");
			ContentValues values = new ContentValues();
			values.put("name", "카테고리추가");
			mDatabase.insert("categoryNames", null, values);
			values.put("name", "기타...");
			mDatabase.insert("categoryNames", null, values);
		}
//		startManagingCursor(c2);
		c2.close();

	}

	private void closeData() {
		if (mDatabase != null)
			mDatabase.close();
	}

	// @Override
	// protected void onListItemClick(ListView l, View v, int position, long id)
	// {
	// ((SpeechListAdapter) getListAdapter()).toggle(position);
	// }

	public static String setDateFormat(long cdate) {
		String textDate = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		textDate = sdf.format(cdate);
		return textDate;
	}

	private class SpeechListAdapter extends BaseAdapter {

		private String[] delete_ids = null;
		private boolean[] states = null;

		public SpeechListAdapter(Context context) {
			mContext = context;
			setStringArray();
			states = new boolean[list.size()];
			delete_ids = new String[list.size()];
		}

		private void setStringArray() {
			for (int i = 0; i < list.size(); i++) {

				mExpanded.add(false);
				isModify = false;
			}
		}

		public int getCount() {
			return StoryPage.list.size();
		}

		public StoryVO getItem(int position) {
			return StoryPage.list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		SpeechView speechView;

		public View getView(int position, View convertView, ViewGroup parent) {

			final int chposition = position;
			String data = getItem(position).getQr_img();
			byte[] bytePlainOrg = Base64.decode(data, 0);
			ByteArrayInputStream inStream = new ByteArrayInputStream(
					bytePlainOrg);
			Bitmap bm = BitmapFactory.decodeStream(inStream);

			if (convertView == null) {
				speechView = new SpeechView(mContext, getItem(position).getWebTitle(), setDateFormat(getItem(position).getCdate()),
						getItem(position).getStory(), getItem(position)
								.getQr_img(), mExpanded.get(position), isModify);
				speechView.setQrCode(bm);

			} else {
				speechView = (SpeechView) convertView;
				speechView.setTitle(getItem(position).getWebTitle());
				speechView
						.setsDate(setDateFormat(getItem(position).getCdate()));
				speechView.setDialogue(getItem(position).getStory());
				speechView.setQrCode(bm);
				speechView.setExpanded(mExpanded.get(position));
				speechView.setModify(isModify);
			}
			speechView.getmModify().setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getApplicationContext(),
							StoryWritePage.class);
					Log.i("story", "story id...." + getItem(chposition).getId());
					Log.i("story", "position...." + chposition);
					intent.putExtra("id", getItem(chposition).getId());
					intent.putExtra("position", chposition);
					startActivity(intent);
				}
			});
			speechView.getMURLText().setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					Log.i("story", "story id...." + getItem(chposition).getId());
					Log.i("story", "position...." + chposition);
					((SpeechListAdapter) getListAdapter()).toggle(chposition);
					return false;
				}
			});
			// speechView.getWdateText().setOnTouchListener(new
			// OnTouchListener() {
			//
			// @Override
			// public boolean onTouch(View v, MotionEvent event) {
			// Log.i("story", "story id...." + getItem(chposition).getId());
			// Log.i("story", "position...." + chposition);
			// ((SpeechListAdapter) getListAdapter()).toggle(chposition);
			// return false;
			// }
			// });
			// speechView.getStory_row().setOnTouchListener(new
			// OnTouchListener() {
			//
			// @Override
			// public boolean onTouch(View v, MotionEvent event) {
			// Log.i("story", "story id...." + getItem(chposition).getId());
			// Log.i("story", "position...." + chposition);
			// ((SpeechListAdapter) getListAdapter()).toggle(chposition);
			// return false;
			// }
			// });

			speechView.getmLinkBtn().setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Log.i("story", "story link id...."
							+ getItem(chposition).getId());
					Log.i("story", "story link ...."
							+ getItem(chposition).getUrl());

					if (getItem(chposition).getUrl().startsWith("http://") || getIntent().getStringExtra("url").startsWith("https://")) {
						launchIntent(new Intent(Intent.ACTION_VIEW, Uri
								.parse(getItem(chposition).getUrl())));
					} else {
						Intent intent = new Intent(getApplicationContext(),
								TextViewerPage.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("text", getItem(chposition).getUrl());
						startActivity(intent);
					}

				}
			});

			speechView.mDelete
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {

							states[chposition] = isChecked;

							// Log.i("story", "states[" + chposition + "] : "
							// +
							// states[chposition]+"....id:"+getItem(chposition).getId());
							if (isChecked) {
								delete_ids[chposition] = getItem(chposition)
										.getId() + "";
							} else {
								delete_ids[chposition] = null;
							}
							String temp = "";
							for (int i = 0; i < delete_ids.length; i++) {
								temp = temp.concat("delete_ids[" + i + "]:"
										+ delete_ids[i] + ", ");

							}
							Log.i("story", temp);
						}
					});

			// Log.i("story", "states["+position+"] : "+states[position]);

			if (states[position]) {
				speechView.mDelete.setChecked(true);

			} else {
				speechView.mDelete.setChecked(false);
			}

			return speechView;
		}

		public boolean isModify() {
			return isModify;
		}

		public void editToggle(Button btn) {
			isModify = !isModify;
			if (isModify) {
				btn.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.story_delete));
			} else {
				btn.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.story_edit));
			}
			if (isModify) {
				for (int i = 0; i < list.size(); i++) {
					mExpanded.set(i, false);
				}
			}
			notifyDataSetChanged();
		}

		public void toggle(int position) {
			if (isModify) {
				return;
			}
			mExpanded.set(position, !mExpanded.get(position));

			// 1. 펼쳐질때만 글쓰기 화면으로 이동시키기.mExpanded[position]>>>true 일때.
			// 2. 글쓴 내용이 있는지 없는지 비교해서 없을때만 글쓰기 화면으로 이동시키기.isStory>>true일때
			boolean isStory = haveAStory(getItem(position).getId());

			// 3. 1.2번 동시만족일때만 글쓰기로 이동.
			if (mExpanded.get(position) && isStory) {
				/*
				 * startActivity(new Intent(getApplicationContext(),
				 * StoryWritePage.class).putExtra("id",
				 * getItem(position).getId()));
				 */

				Intent intent = new Intent(getApplicationContext(),
						StoryWritePage.class);
				intent.putExtra("id", getItem(position).getId());
				intent.putExtra("position", position);
				startActivity(intent);

			}
			// else {
			// if (getItem(position).getUrl().startsWith("http://")) {
			// launchIntent(new Intent(Intent.ACTION_VIEW, Uri
			// .parse(getItem(position).getUrl())));
			// } else {
			// Intent intent = new Intent(getApplicationContext(),
			// TextViewerPage.class);
			// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// intent.putExtra("text", getItem(position).getUrl());
			// startActivity(intent);
			// }
			// }
			notifyDataSetChanged();
		}

		private boolean haveAStory(int id) {
			openData();
			Cursor c = mDatabase.query("qrStory", null, "id=?",
					new String[] { id + "" }, null, null, null);
			c.moveToFirst();
			String story = c.getString(c.getColumnIndex("story"));
			boolean isStory = false;
			if (story == null) {
				isStory = true;
			}
			c.close();
			return isStory;
		}
	}

	private class SpeechView extends LinearLayout {
		LayoutInflater Inflater;

		private ImageView qrcode;
		private TextView sTitle;
		private TextView sDate;
		private Button mlinkBtn;
		private TextView mDialogue;
		CheckBox mDelete;
		private Button mModify;
		private TextView mURLText;
		private TextView wdateText;
		private LinearLayout story_row;

		public SpeechView(Context context, String title, String date,
				String dialogue, String qr, boolean expanded, boolean isModify) {
			super(context);

			this.setOrientation(VERTICAL);

			this.setBackgroundColor(Color.rgb(30, 30, 30));

			Inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View v = Inflater.inflate(R.layout.story_list, this, false);

			sTitle = (TextView) v.findViewById(R.id.story_title);
			sTitle.setText(title);

			sDate = (TextView) v.findViewById(R.id.story_date);
			sDate.setText(date);

			mlinkBtn = (Button) v.findViewById(R.id.linkBtn);
			// ///////
			mlinkBtn.setVisibility(View.VISIBLE);

			qrcode = (ImageView) v.findViewById(R.id.story_qrcode);

			mModify = (Button) v.findViewById(R.id.story_modify);
			mDelete = (CheckBox) v.findViewById(R.id.story_delete);
			mURLText = (TextView) v.findViewById(R.id.story_title);
			wdateText = (TextView) v.findViewById(R.id.story_date);
			story_row = (LinearLayout) v.findViewById(R.id.story_row);

			addView(v);

			mDialogue = new TextView(context);
			mDialogue.setPadding(30, 15, 0, 15);
			mDialogue.setTextSize(15);
			mDialogue.setText(dialogue);
			mDialogue.setTextColor(Color.WHITE);
			addView(mDialogue, new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

			mDialogue.setVisibility(expanded ? VISIBLE : GONE);
		}

		public void setModify(boolean Modify) {
			if (Modify) {
				mModify.setVisibility(View.VISIBLE);
				mDelete.setVisibility(View.VISIBLE);
				mlinkBtn.setVisibility(View.GONE);

			} else {
				mModify.setVisibility(View.GONE);
				mDelete.setVisibility(View.GONE);
				// ///////
				mlinkBtn.setVisibility(View.VISIBLE);
			}
		}

		public CheckBox getmDelete() {
			return mDelete;
		}

		public Button getmModify() {
			return mModify;
		}

		public TextView getMURLText() {
			return mURLText;
		}

		public TextView getWdateText() {
			return wdateText;
		}

		public LinearLayout getStory_row() {
			return story_row;
		}

		public Button getmLinkBtn() {
			return mlinkBtn;
		}

		public void setQrCode(Bitmap bm) {
			qrcode.setImageBitmap(bm);
		}

		public void setTitle(String title) {
			sTitle.setText(title);
		}

		public void setsDate(String date) {
			sDate.setText(date);
		}

		public void setDialogue(String words) {
			mDialogue.setText(words);
		}

		public void setExpanded(boolean expanded) {
			mDialogue.setVisibility(expanded ? VISIBLE : GONE);
		}
	}
}